package com.bangcommunity.bbframe.sdm.web.shiro.filter;

import com.bangcommunity.bbframe.common.base.BaseResult;
import com.bangcommunity.bbframe.sdm.utils.JacksonUtil;
import com.bangcommunity.bbframe.sdm.utils.RequestUtils;
import com.bangcommunity.bbframe.sdm.web.exception.RestConf;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义登出
 */
public class CustomLogoutFilter extends LogoutFilter {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        try {
            Subject subject = getSubject(request, response);
            subject.logout();
            boolean ajaxRequest = RequestUtils.isAjaxRequest((HttpServletRequest) request);
            if (ajaxRequest || RestConf.isRest) {
                BaseResult result = BaseResult.success("logout success");
                HttpServletResponse res = (HttpServletResponse) response;
                res.setHeader("Content-Type", "application/json;charset=utf-8");
                PrintWriter out = res.getWriter();
                JacksonUtil jsonMapper = new JacksonUtil();
                out.write(jsonMapper.toJson(result));
                out.flush();
                out.close();
            } else {
                String redirectUrl = getRedirectUrl(request, response, subject);
                super.issueRedirect(request, response, redirectUrl);
            }
        } catch (Exception e1) {
            logger.error("onLoginFailure response exceptioon: ", e1);
        }
        return false;
    }
}
